package cn.xuqiudong.sso.common.util;

import cn.xuqiudong.common.util.CookieUtil;
import cn.xuqiudong.common.util.JsonUtil;
import cn.xuqiudong.sso.common.constant.SsoConstant;
import cn.xuqiudong.sso.common.model.SsoUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;

/**
 * 描述:
 *  cas sso中的cookie处理
 * @author Vic.xu
 * @since 2024-06-20 14:30
 */
public class SsoCookieUtil {

    /**
     * 记住我：把user转为token, 存入cookie
     *
     * @param user SsoUser
     * @return tokenHex
     */
    public static String rememberMe(SsoUser user, HttpServletResponse response) {
        if (user == null || response == null) {
            return null;
        }
        String tokenJson = JsonUtil.toJson(user);
        String tokenHex = new BigInteger(tokenJson.getBytes(StandardCharsets.UTF_8)).toString(16);
        CookieUtil.set(response, SsoConstant.PRINCIPAL_IN_COOKIE, tokenHex, true);
        return tokenHex;
    }

    /**
     * 移除 记住我
     */
    public static void removeRememberMe(HttpServletRequest request, HttpServletResponse response) {
        CookieUtil.remove(request, response, SsoConstant.PRINCIPAL_IN_COOKIE);
    }


    /**
     * 获取coolie中记住我的 SsoUser
     * @return
     */
    public static SsoUser rememberedUser(HttpServletRequest request) {
        SsoUser user = null;
        String cookieToken = CookieUtil.getValue(request, SsoConstant.PRINCIPAL_IN_COOKIE);
        if (cookieToken != null) {
            String tokenJson = new String(new BigInteger(cookieToken, 16).toByteArray(), StandardCharsets.UTF_8); // username_password(md5)
            user = JsonUtil.jsonToObject(tokenJson, SsoUser.class);
        }
        return user;
    }
}
